/**
 * ...
 * @author Hatshepsout
 */

function ImageFileReader()
{
	this._init();
}

Tomahawk.registerClass( ImageFileReader, "ImageFileReader" );
Tomahawk.extend( "ImageFileReader", "EventDispatcher" );

ImageFileReader.prototype._element = null;

ImageFileReader.prototype._init = function()
{
	this._element = document.createElement("input");
	this._element.type = "file";
	this._element.style.visibility = "hidden";
	this._element.addEventListener('change', this._handleFileSelect.bind(this), false);
};

ImageFileReader.prototype.start = function()
{
	var element = this._element;
	document.body.appendChild(element);
	element.click();
	//
    //if (document.createEventObject){
		//
        // dispatch for IE
        //var evt = document.createEventObject();
        //element.fireEvent('onclick',evt)
    //}
    //else{
        // dispatch for firefox + others
        //var evt = document.createEvent("HTMLEvents");
        //evt.initEvent("click", true, true ); // event type,bubbling,cancelable
        //element.dispatchEvent(evt);
    //}
};

ImageFileReader.prototype._handleFileSelect = function(event)
{
	var files = event.target.files; // FileList object
	var currentFile = null;
	var max = files.length;
	var i = 0;
	var reader = null;
	    
	// Loop through the FileList and render image files as thumbnails.
    for (i = 0; i < max; i++) 
	{
		currentFile = files[i]
		// Only process image files.
		
		if (!currentFile.type.match('image.*'))
			continue;

		reader = new FileReader();
		reader.onload= this._readFileHandler.bind(this,reader,currentFile);

		// Read in the image file as a data URL.
		reader.readAsDataURL(currentFile);
    }
};

ImageFileReader.prototype._readFileHandler = function(reader,file)
{
	var img = new Image();
	img.onload = this._imageLoadedHandler.bind(this,img,file,reader);
	img.src = reader.result;
};

ImageFileReader.prototype._imageLoadedHandler = function(img,file,reader)
{
	var event = new EditorEvent(EditorEvent.IMAGE_LOADED,true,true);
	event.image = img;
	event.file = file;
	event.data = reader.result;
	this.dispatchEvent( event );
	document.body.removeChild(this._element);
};

ImageFileReader.prototype.createDOMElement = function(id,name)
{
	var el = document.createElement("input");
	el.type = "file";
	el.id = id;
	el.name = name;
	el.multiple = true;
	
	return el;
};


